package gdiff_string;

sub new {
shift;
my $self={};
my $str=$_[0];

	$self->{offset}=0;
	if(defined($str)) {
		$self->{data}=$str;
		$self->{size}=length($str);
	} else {
		$self->{data}="";
		$self->{size}=0;
	}
	bless($self);
	$self->{DEBUG}=0;
	$self->{DEBUG}=1 if exists($::ENV{DEBUG}) && $::ENV{DEBUG}==1;
	return $self;
}

sub read($\\$$;$) {
my $self=$_[0];
my ($bufref,$len,$off)=($_[1],$_[2],$_[3]);

	if($len<=0) {
		print "0 returned since negative length\n" if $self->{DEBUG};
		return(0);
	}
	my $size=$self->{size};
	my $offset=$self->{offset};
	print "Requested $len bytes [filesize=$size,offset=$offset]\n" if $self->{DEBUG};

	if($offset>=$size) {
		print "0 returned since offset [$offset] > file size [$size]\n" if $self->{DEBUG};
		return 0;
	}
	if($offset+$len>$size) {
		$len=$size-$offset+1;
	}

	if(defined($off) && $off!=0) {
		# substr($$bufref,$off,$len)=substr($self->{data},$offset,$len);
		substr($_[1],$off,$len)=substr($self->{data},$offset,$len);
	} else {
		# $$bufref=substr($self->{data},$offset,$len);
		$_[1]=$$bufref=substr($self->{data},$offset,$len);
	}
	$self->{offset}=$offset+$len;
	print "Returned $len bytes , offset changed to $self->{offset}\n" if $self->{DEBUG};
	return $len;
}

sub write($$$;$) {
my $self=shift;
my ($bufref,$len,$off)=@_;

	return(0) if $len<=0;
	my $size=$self->{size};
	my $offset=$self->{offset};

	if($offset+$len>=$size) {
		# Pad with 0's
		my $p=$offset-$size+$len;
		$self->{data}.= chr(0) x $p;
		$size=$offset+$len;
		$self->{size}=$size;
	}
	my $str;
	if($off) {
		$str=substr($bufref,$off);
	} else {
		$str=$bufref;
	}
	$str.= chr(0) x $len;
	$str=substr($str,0,$len);
	substr($self->{data},$offset,$len)=$str;
	$self->{offset}=$offset+$len;
	return $len;
}

sub tell {
my $self=shift;

	return $self->{offset};
}

sub seek($$$) {
my $self=shift;
my ($pos,$relto)=@_;

	if($relto==0) {
		$self->{offset}=$pos;
		return 1;
	}
	if($relto==1) {
		$self->{offset}+=$pos;
		return 1;
	}
	if($relto==2) {
		$self->{offset}=$self->{size}+$pos;
		return 1;
	}
	return 0;
}

sub stringify {
my $self=shift;
	return $self->{data};
}

1;

